<?php
/**
 * tpshop
 * ============================================================================
 * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 聂晓克      
 * Date: 2017-12-14
 */
namespace app\admin\controller;
use app\admin\model\Goods;
use think\Page;
use app\admin\logic\GoodsLogic;
use app\admin\logic\MiniLogic;
use app\admin\logic\ArticleCatLogic;
use think\Db;

class MiniPage extends Base{

    /**
     * 首页的基础数据
     * @return mixed
     */
	public function index(){

        //--产品
        $categoryList = Db::name('goods_category')->getField('id,name',true);
        $this->assign('categoryList', $categoryList);
        $Goods = new Goods();
        $count = $Goods->count();
        $Page = new Page($count, 10);
        $goodsList = $Goods->order('goods_id DESC')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $this->assign('goodsList', $goodsList);//赋值分页输出
        $this->assign('count', $Page->totalPages);//赋值分页输出

        //--分类
        $cat_list = Db::name('goods_category')->where("parent_id = 0")->select(); // 已经改成联动菜单
        $this->assign('cat_list', $cat_list);


        //--文章
        $art = M("article");
        $art_count = $art->count();
        $Page2 = new Page($art_count, 10);
        $article_list = $art->order('sort DESC')->limit($Page->firstRow . ',' . $Page->listRows)->select();

        $art_cat_list = Db::name('article_cat')->getField('cat_id,cat_name',true);
        $this->assign('art_cat_list', $art_cat_list);
        $this->assign('ArticleList', $article_list);//赋值分页输出
        $this->assign('count2', $Page2->totalPages);//赋值分页输出


        $list = Db::name('goods_category')->where('is_show',1)->order('parent_id_path asc,sort_order desc')->field('id,mobile_name,name,parent_id,parent_id_path,level,sort_order')->select();
        $tree = build_tree($list,0);
        $this->assign('cat_tree',$tree);

        $id = I('id');
        $editData = Db::name('mini_template')->where('id',$id)->find();
        if($editData != false){
            $this->assign('html',htmlspecialchars_decode($editData['template_html']));
            $this->assign('template_name',$editData['template_name']);
            $this->assign('id',$id);
            $this->assign('info',htmlspecialchars_decode($editData['template_json']));
        }

        return $this->fetch();
	}

	//自定义页面列表页
	public function pageList(){

	    $list = Db::name('mini_template')->select();
	    $this->assign('list',$list);

        return $this->fetch();
	}

    /**
     * 分页与查询数据
     * @return \think\response\Json
     */
	public function ajaxGoodsList(){
        $keywords = I('goods_name');

        $categoryList = Db::name('goods_category')->getField('id,name',true);


        if ($keywords) {
            $where['goods_name|keywords'] = array('like', '%' . $keywords . '%');
        }

        $Goods = new Goods();
        $count = $Goods->where($where)->count();
        $Page = new Page($count, 10);
        $goodsList = $Goods->where($where)->order('goods_id DESC')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $show = $Page->show();//分页显示输出

        $html = '';
        foreach ($goodsList as $value){

            $catName = $categoryList[$value[cat_id]];
            $html = $html."<ul class='p-goods-item'>
                        <li class='pi-li0'><input type='checkbox' value='$value[goods_id]' /></li>
                        <li class='pi-li1'>$value[goods_id]</li>
                        <li class='pi-li2'>$value[goods_name]</li>
                        <li class='pi-li3'><img src='$value[original_img]' alt='' /></li>
                        <li class='pi-li4'>$catName</li>
                        <li class='pi-li4'>$value[shop_price]</li>
                        <li class='pi-li4'>$value[store_count]</li>
                    </ul>";
        }

        $html = '<div class="p-goods-scroll">'.$html.'</div>';

        return json(array('status'=>1,'result'=>array('html'=>$html,'count'=>$Page->totalPages)));
    }

    /**
     * 文章分页查询
     * @return \think\response\Json
     */
    public function ajaxArticleList(){
        $keywords = I('keywords');

        $categoryList = Db::name('article_cat')->getField('cat_id,cat_name',true);


        if ($keywords) {
            $where['title'] = array('like', '%' . $keywords . '%');
        }

        $art = M("article");
        $count = $art->where($where)->count();
        $Page = new Page($count, 10);
        $articleList = $art->where($where)->order('sort DESC')->limit($Page->firstRow . ',' . $Page->listRows)->select();

        $html = '';
        foreach ($articleList as $value){

            $catName = $categoryList[$value[cat_id]];
            $html = $html."<ul class='p-goods-item'>
                        <li class='pi-li0'><input type='checkbox' value='$value[article_id]' /></li>
                        <li class='pi-li1'>$value[article_id]</li>
                        <li class='pi-li2'>$value[title]</li>
                        <li class='pi-li3'><img src='$value[thumb]' alt='' /></li>
                        <li class='pi-li4'>$catName</li>
                    </ul>";
        }

        $html = '<div class="p-goods-scroll">'.$html.'</div>';

        return json(array('status'=>1,'result'=>array('html'=>$html,'count'=>$Page->totalPages)));
    }

    //商品列表板块参数设置
    public function goods_list_block(){
        $param = I("post.");
        if(!empty($param['ids'])){
            $map['cat_id'] = array('in',$param['ids']);
        }
        if(!empty($param['max_price']) && !empty($param['min_price'])){
            $map['shop_price'] = array('between',array($param['min_price'],$param['max_price']));
        }
        $map1 = '';
        if(!empty($param['label'])){
            $map1 =$param['label'].'=1 ';
        }

        if(!empty($param['goods'])){
            $map['goods_id'] = array('in',$param['goods']);
        }

        switch ($param['order']){
            case 0: $order = 'sales_sum desc';
            break;
            case 1: $order = 'sales_num asc';
            break;
            case 2: $order = 'shop_price desc';
            break;
            case 3: $order = 'shop_price asc';
            break;
            case 4: $order = 'last_update desc';
            break;
            case 5: $order = 'last_update asc';
            break;
            default:$order = 'id asc';
        }

        $list = Db::name('goods')->where($map)->where($map1)->limit($param['num'])->order($order)->select();


        $html = '';
        foreach ($list as $value){
            $html =  $html. "<li>
                    <a class='tpdm-goods-pic' href='javascript:;'>
                    <img src='$value[original_img]' alt=''></a>
                    <a href='javascript:;' class='tpdm-goods-name'>$value[goods_name]</a>
                    <div class='tpdm-goods-des'>
                        <div class='tpdm-goods-price'>￥$value[shop_price]</div>
                        <a class='tpdm-goods-like' href='javascript:;'>看相似</a></div>
                </li>";
        }

        $this->ajaxReturn(['status' => 1, 'msg' => '成功','result' =>$html ]);
    }

	/*
	*保存编辑完成后的信息
	*/
	public function add_data(){
 		$param=I('post.');
 		//print_r($param);exit();
 		$html=$param['html'];
 		$html=str_replace("\n"," ",$html);

 		$data['add_time']=time();
 		$data['template_html']=$html;
 		$data['template_json']=htmlspecialchars_decode($param['info']);
 		$data['template_name']=$param['template_name'];
 		if(empty($param['edit_id'])){
 		    $res=M('mini_template')->add($data);
        }else{
            $res=M('mini_template')->where('id',$param['edit_id'])->save($data);
        }
 		if($res){
 			$this->ajaxReturn(['status'=>1,'msg'=>'添加成功','result'=>empty($param['edit_id'])? $res:$param['edit_id']]);
 		}else{
            $this->ajaxReturn(['status'=>0,'msg'=>'添加失败']);
 		}
	}

	//设置首页
	public function set_show(){
		$data=I('post.');
		if($data['status']==0){
			$sql='update tp_mini_template set is_show=if(id='.$data['id'].', 1, 0)';
		}
		if($data['status']==1){
			$sql='update tp_mini_template set is_show=0 where id='.$data['id'];
		}
		$result=DB::execute($sql);
		if($result){
			$this->ajaxReturn(['status' => 1, 'msg' => '成功','result' => 1]);
		}else{
			$this->ajaxReturn(['status' => 0, 'msg' => '失败','result' => 0]);
		}
	}

	//删除页面
	public function delete(){
		$id=I('post.id');
		if($id){
			$r = D('mini_template')->where('id', $id)->delete();
    		exit(json_encode(1));
		}
	}

	
	//获取秒杀活动数据
	public function get_flash(){
        //秒杀商品
        $now_time = time();  //当前时间
        if(is_int($now_time/7200)){      //双整点时间，如：10:00, 12:00
            $start_time = $now_time;
        }else{
            $start_time = floor($now_time/7200)*7200; //取得前一个双整点时间
        }
        $end_time = $start_time+7200;   //结束时间
        $flash_sale_list = M('goods')->alias('g')
            ->field('g.goods_id,f.price,s.item_id')
            ->join('flash_sale f','g.goods_id = f.goods_id','LEFT')
            ->join('__SPEC_GOODS_PRICE__ s','s.prom_id = f.id AND g.goods_id = s.goods_id','LEFT')
            ->where("start_time = $start_time and end_time = $end_time")
            ->limit(3)->select();
        dump($flash_sale_list);exit();
	}

    /**
     *  商品分类列表
     */
    public function categoryList(){
        $GoodsLogic = new MiniLogic();
        $cat_list = $GoodsLogic->goods_cat_list();
        $this->assign('cat_list',$cat_list);
        return $this->fetch();
    }

    /**
     * 添加修改商品分类
     * 手动拷贝分类正则 ([\u4e00-\u9fa5/\w]+)  ('393','$1'),
     * select * from tp_goods_category where id = 393
    select * from tp_goods_category where parent_id = 393
    update tp_goods_category  set parent_id_path = concat_ws('_','0_76_393',id),`level` = 3 where parent_id = 393
    insert into `tp_goods_category` (`parent_id`,`name`) values
    ('393','时尚饰品'),
     */
    public function addEditCategory(){

        //--产品
        $categoryList = Db::name('goods_category')->getField('id,name',true);
        $this->assign('categoryList', $categoryList);
        $Goods = new Goods();
        $count = $Goods->count();
        $Page = new Page($count, 10);
        $goodsList = $Goods->order('goods_id DESC')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $this->assign('goodsList', $goodsList);//赋值分页输出
        $this->assign('count', $Page->totalPages);//赋值分页输出

        //--分类
        $cat_list = Db::name('goods_category')->where("parent_id = 0")->select(); // 已经改成联动菜单
        $this->assign('cat_list', $cat_list);


        //--文章
        $art = M("article");
        $art_count = $art->count();
        $Page2 = new Page($art_count, 10);
        $article_list = $art->order('sort DESC')->limit($Page->firstRow . ',' . $Page->listRows)->select();

        $art_cat_list = Db::name('article_cat')->getField('cat_id,cat_name',true);
        $this->assign('art_cat_list', $art_cat_list);
        $this->assign('ArticleList', $article_list);//赋值分页输出
        $this->assign('count2', $Page2->totalPages);//赋值分页输出


        $list = Db::name('goods_category')->where('is_show',1)->order('parent_id_path asc,sort_order desc')->field('id,mobile_name,name,parent_id,parent_id_path,level,sort_order')->select();
        $tree = build_tree($list,0);
        $this->assign('cat_tree',$tree);


        $ArticleCat = new ArticleCatLogic();
        $art_cat_list = $ArticleCat->article_cat_list(0, 0, false);
        $this->assign('art1_cat_list',$art_cat_list);

        $GoodsLogic = new MiniLogic();
        if(IS_GET)
        {
            $goods_category_info = D('MiniCategory')->where('id='.I('GET.id',0))->find();
            $this->assign('goods_category_info',$goods_category_info);

            $all_type = M('mini_category')->where("level<3")->getField('id,name,parent_id');//上级分类数据集，限制3级分类，那么只拿前两级作为上级选择
            if(!empty($all_type)){
                $parent_id = empty($goods_category_info) ? I('parent_id',0) : $goods_category_info['parent_id'];
                $all_type = $GoodsLogic->getCatTree($all_type);
                $cat_select = $GoodsLogic->exportTree($all_type,0,$parent_id);
                $this->assign('cat_select',$cat_select);
            }

            //$cat_list = M('goods_category')->where("parent_id = 0")->select();
            //$this->assign('cat_list',$cat_list);
            return $this->fetch('_category');
            exit;
        }

        $GoodsCategory = D('MiniCategory'); //

        $type = I('id') > 0 ? 2 : 1; // 标识自动验证时的 场景 1 表示插入 2 表示更新
        //ajax提交验证
        if(I('is_ajax') == 1)
        {
            // 数据验证
            $validate = \think\Loader::validate('MiniCategory');
            if(!$validate->batch()->check(input('post.')))
            {
                $error = $validate->getError();
                $error_msg = array_values($error);
                $return_arr = array(
                    'status' => -1,
                    'msg' => $error_msg[0],
                    'data' => $error,
                );
                $this->ajaxReturn($return_arr);
            } else {
                $GoodsCategory->data(input('post.'),true); // 收集数据
                $GoodsCategory->parent_id = I('parent_id');

                //查找同级分类是否有重复分类
                $par_id = ($GoodsCategory->parent_id > 0) ? $GoodsCategory->parent_id : 0;
                $sameCateWhere = ['parent_id'=>$par_id , 'name'=>$GoodsCategory['name']];
                $GoodsCategory->id && $sameCateWhere['id'] = array('<>' , $GoodsCategory->id);
                $same_cate = M('MiniCategory')->where($sameCateWhere)->find();
                if($same_cate){
                    $return_arr = array('status' => 0,'msg' => '同级已有相同分类存在','data' => '');
                    $this->ajaxReturn($return_arr);
                }

                if ($GoodsCategory->id > 0 && $GoodsCategory->parent_id == $GoodsCategory->id) {
                    //  编辑
                    $return_arr = array('status' => 0,'msg' => '上级分类不能为自己','data' => '',);
                    $this->ajaxReturn($return_arr);
                }

                $url = $_POST['url'];
                if(!empty($url)){
                    parse_str($url, $arr);
                    $GoodsCategory->model = $arr['a'];
                    $GoodsCategory->model_id = $arr['id'];
                }

                if ($type == 2)
                {
                    $GoodsCategory->isUpdate(true)->save(); // 写入数据到数据库
                    $GoodsLogic->refresh_cat(I('id'));
                }
                else
                {
                    $GoodsCategory->save(); // 写入数据到数据库
                    $insert_id = $GoodsCategory->getLastInsID();
                    $GoodsLogic->refresh_cat($insert_id);
                }
                $return_arr = array(
                    'status' => 1,
                    'msg'   => '操作成功',
                    'data'  => array('url'=>U('Admin/MiniPage/categoryList')),
                );
                $this->ajaxReturn($return_arr);

            }
        }

    }

    /**
     * 获取商品分类 的帅选规格 复选框
     */
    public function ajaxGetSpecList(){
        $GoodsLogic = new GoodsLogic();
        $_REQUEST['category_id'] = $_REQUEST['category_id'] ? $_REQUEST['category_id'] : 0;
        $filter_spec = M('MiniCategory')->where("id = ".$_REQUEST['category_id'])->getField('filter_spec');
        $filter_spec_arr = explode(',',$filter_spec);
        $str = $GoodsLogic->GetSpecCheckboxList($_REQUEST['type_id'],$filter_spec_arr);
        $str = $str ? $str : '没有可帅选的商品规格';
        exit($str);
    }

    /**
     * 获取商品分类 的帅选属性 复选框
     */
    public function ajaxGetAttrList(){
        $GoodsLogic = new MiniLogic();
        $_REQUEST['category_id'] = $_REQUEST['category_id'] ? $_REQUEST['category_id'] : 0;
        $filter_attr = M('MiniCategory')->where("id = ".$_REQUEST['category_id'])->getField('filter_attr');
        $filter_attr_arr = explode(',',$filter_attr);
        $str = $GoodsLogic->GetAttrCheckboxList($_REQUEST['type_id'],$filter_attr_arr);
        $str = $str ? $str : '没有可帅选的商品属性';
        exit($str);
    }

    /**
     * 删除分类
     */
    public function delGoodsCategory(){
        $ids = I('post.ids','');
        empty($ids) &&  $this->ajaxReturn(['status' => -1,'msg' =>"非法操作！",'data'  =>'']);
        // 判断子分类
        $count = Db::name("mini_category")->where("parent_id = {$ids}")->count("id");
        $count > 0 && $this->ajaxReturn(['status' => -1,'msg' =>'该分类下还有分类不得删除!']);

        // 删除分类
        DB::name('mini_category')->where('id',$ids)->delete();
        $this->ajaxReturn(['status' => 1,'msg' =>'操作成功','url'=>U('Admin/Goods/categoryList')]);
    }


}
?>